package cn.tit.ias.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.tools.ant.taskdefs.Available;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.tit.ias.entity.AssetInfo;
import cn.tit.ias.entity.DicProfitLossInfo;
import cn.tit.ias.mapper.AssetInfoMapper;
import cn.tit.ias.mapper.DicProfitLossInfoMapper;
import cn.tit.ias.service.AssetInfoService;
import cn.tit.ias.service.ExcelService;
import cn.tit.ias.util.handlexcel.FileUtil;
import cn.tit.ias.util.handlexcel.HandleAssetNumRange;
import cn.tit.ias.util.handlexcel.HandleExcelUtil_;
import cn.tit.ias.util.handlexcel.easyexcel.EasyExcelHanderUtil;
/**
 * 
 *  
 * @Description:ExcelService接口实现类   
 * @author: maotao 
 * @date:   2019年8月3日 下午12:15:47       
 *
 */
@Service
public class ExcelServiceImpl implements ExcelService{

	@Autowired
	AssetInfoMapper assetInfoMapper;
	@Autowired
	DicProfitLossInfoMapper profitLossMapper;
	@Autowired
	AssetInfoService assetInfoService;
	private boolean checkResult = false;
	
	/**
	 * 
	 * <p>Title: importExcel</p>   
	 * <p>Description:导入本地资产表到系统的临时表中 </p>   
	 * @param file 上传文件
	 * @param departNum 部门编号
	 */
	@Override
	public Map<String, Object> importExcel(File file,String departNum) {
		// 导入数据总条数
		int total = 0;
		// 验证成功总数
		int available =0;
		// 导入有效数据总数
		int importSuccess = 0;
		// 执行sql的状态
		int resultStatus =0;
		// 执行要返回的结果
		Map<String, Object> resultSet = new HashMap<>();
		// 接收sheet
		Map<String, List<Map<String, Object>>> sheet = new HashMap<String, List<Map<String, Object>>>();
		// 接收row
		List<Map<String, Object>> list = new ArrayList<>();
		
		// 将上传转换文件格式转为java IO流的File
		try {
			// 读取excel表格数据
			sheet = HandleExcelUtil_.getFromTotalAssetExcel_1(HandleExcelUtil_.readExcel(file, 1000, 50));
		} catch (IOException | EncryptedDocumentException | InvalidFormatException e) {
			System.out.println("文件转换失败");
			e.printStackTrace();
		}
		// excel表格中所有数据
		list = sheet.get("sheet");
		total = list.size();
		List<Map<String, Object>> newList = new ArrayList<>();
	    // 迭代出每一行数据
		Iterator<Map<String, Object>> iterator = list.iterator();
		while (iterator.hasNext()) {
			// column
			Map<String, Object> newMap = new HashMap<>();
			newMap = iterator.next();
			newMap.put("departNum", departNum);
			// 验证导入的每一条资产是否满足条件
			try {
				if (newMap.get("imAssetRange") != "" && newMap.get("imAssetRange") != null
						&& newMap.get("imUnitName") != "" && newMap.get("imUnitName") != null
						&& newMap.get("imDocumentNum") != "" && newMap.get("imDocumentNum") != null
						&& newMap.get("imAssetName") != "" && newMap.get("imAssetName") != null
						&& newMap.get("imAssetModel") != "" && newMap.get("imAssetModel") != null
						&& newMap.get("imAssetPrice") != "" && newMap.get("imAssetPrice") != null
						&& newMap.get("imFactory") != "" && newMap.get("imFactory") != null
						&& newMap.get("imBuyDate") != "" && newMap.get("imBuyDate") != null
						&& newMap.get("imTakePeople") != "" && newMap.get("imTakePeople") != null
						&& newMap.get("imRemark") != "" && newMap.get("imRemark") != null){
					System.out.println(newMap.get("imAssetRange"));
					resultStatus = assetInfoMapper.importAssetToTemportaryTable(newMap);
					importSuccess += resultStatus;
					available++;
				}else{
					newList.add(newMap);
				}
			} catch (Exception e) {
				System.out.println("失败");
				newList.add(newMap);
			}
			
		}
		resultSet.put("total", total);
		resultSet.put("available", available);
		resultSet.put("importSuccess", importSuccess);
		resultSet.put("errorValiable", newList);
		return resultSet;
	}
	/**
	 * 
	 * <p>Title: inLoadToAsset</p>   
	 * <p>Description: 将导入到临时表中的数据通过处理转存到资产表中</p>   
	 * @param departNum 部门编号
	 * @return   
	 */
	@Override
	public Map<String, Object> inLoadToAsset(String departNum) {
		// 存放处理成功后的数据总数
		int total = 0;
		// 存放执行结果状态
		Map<String, Object>resultSet = new HashMap<>();
		// 获取临时表中符合条件的数据
		List<Map<String, Object>> list = new ArrayList<>();
		list = assetInfoMapper.getTemportaryTable(departNum);
		// 获取损益类型 名称对应的编号 以键值对进行存放，名称为键，编号为值
		Map<String, Object>profitLossType = new HashMap<>();
		List<DicProfitLossInfo> profitLossInfos = profitLossMapper.listAllObject();
		for (int i = 0; i < profitLossInfos.size(); i++) {
			profitLossType.put(profitLossInfos.get(i).getDicProfitLossName(), profitLossInfos.get(i).getDicProfitLossNum());
		}
		
		// 清空临时表
		assetInfoMapper.clearImportAssetTemportaryTable(departNum);
		// 获取处理后的资产信息
		List<AssetInfo>assets;
		assets=HandleAssetNumRange.handleExcel(list,profitLossType);
		total = assets.size();
		// 批量插入数据库中的资产表
		try {
			assetInfoMapper.addObjectByBranch(assets);
		} catch (Exception e) {
			resultSet.put("msg","有数据失败");
			System.out.println("有无效数据");
		}
		resultSet.put("total",total);
		return resultSet;
	}
	@Override
	public boolean checkExcelFormat(File file) throws EncryptedDocumentException, InvalidFormatException, FileNotFoundException, IOException {
		checkResult = HandleExcelUtil_.checkExcelFormat(HandleExcelUtil_.readExcel(file, 1000, 50));
		return checkResult;
	}
	@Override
	public void downLoadInventoryExcel(String inventoryBatch, Integer excel_id, HttpServletRequest request,
			HttpServletResponse response) {
		// 获取数据源
		Map<String, Object> dataSource = assetInfoService.getAssetByBatch_v1( 0, -1,inventoryBatch);
		List<Map<String, Object>> data = (List<Map<String, Object>>) dataSource.get("data");
		// 数据源map重新封装 解决java.sql.date转成String
		List<Map<String, Object>> datas = new ArrayList<>();
		for(int i = 0;i < data.size();i++){
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("id", i+1);
			map1.put("inventoryBatch", data.get(i).get("inventoryBatch"));
			map1.put("assetNum", data.get(i).get("assetNum"));
			map1.put("inventoryStatusName", data.get(i).get("inventoryStatusName"));
			map1.put("inventoryDate", (new SimpleDateFormat("yyyy-MM-dd")).format(data.get(i).get("inventoryDate")));
			map1.put("userCount", data.get(i).get("userCount"));
			map1.put("departName", data.get(i).get("departName"));
			map1.put("assetTakePeople", data.get(i).get("assetTakePeople"));
			map1.put("spanAdress", data.get(i).get("spanAdress"));
			map1.put("storeName", data.get(i).get("store"));
			map1.put("dicProfitLossName", data.get(i).get("dicProfitLossName"));
			datas.add(map1);
		}
		// 表格中添加的非列表参数
		Map<String, Object> map = new HashMap<String, Object>();
		// 表头名称
		map.put("depart","计算机工程系");
		// excel模板表路径
		String templateFileName = request.getSession().getServletContext().getRealPath("/") + File.separator+"file"+File.separator+"download"+File.separator+"inventory_form.xlsx";
		// excel工具类对excel模板进行填充
		EasyExcelHanderUtil.ExcelTemplate(templateFileName,excel_id, datas, map, request, response);
		
	}
	@Override
	public void exportErrorAssets(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		List<Map<String, Object>> errorImportInfo = (List<Map<String, Object>>) session.getAttribute("errorImportInfo");
		if(errorImportInfo != null){
			// excel模板表路径
			String templateFileName = request.getSession().getServletContext().getRealPath("/") + File.separator+"file"+File.separator+"download"+File.separator+"error_import_AssetInfo_v1.xlsx";
			Integer excel_id = 3;
			Map<String, Object>map = new HashMap<>();
			// excel工具类对excel模板进行填充
			EasyExcelHanderUtil.ExcelTemplate(templateFileName,excel_id, errorImportInfo, map, request, response);

		}
	}
	
}
